# -*- coding: utf-8 -*-
# Version: Python 3.9.5
# Author: TRIX
# Date: 2021-09-08 18:03:46
# Use: 批量加密Pdf 默认10位数随机密码 可以指定随机密码

import PyPDF3,random,re
def encrypt_pdfs(digit=10,char_freq=[30,30,30,10],*pdf_files):#加密
						    #位数     字符频率
	pdfs_list=list(pdf_files)
	for i,pdf in enumerate(pdfs_list):
		with open(pdf,'rb') as f:
			reader=PyPDF3.PdfFileReader(f)#读取器
			with open(pdf[:-4]+'_encrypt.pdf','wb') as fe:
				writer=PyPDF3.PdfFileWriter()#写入器
				for n in range(reader.numPages):
					writer.addPage(reader.getPage(n))
				password=get_password(digit,char_freq)
				writer.encrypt(password)#写入密码
				print('{}的密码是{}'.format(re.compile(r'[^\\]+\.pdf').search(pdf).group(),password))#匹配pdf文件名
				writer.write(fe)

#生成一个随机密码
def get_password(digit,char_freq):
	#对应关系-变量-字符频率索引
	#小写字母   al 	 			[0]
	#大写字母   au			[1]
	#数字		    n  			[2]
	#符号		    s  	 			[3]
	#10 26 6 最小公倍数 390
	al='qwertyuiopasdfghjklzxcvbnm'*15#26*15
	au='QWERTYUIOPASDFGHJKLZXCVBNM'*15#26
	n='1234567890'*39#10*39
	s='~!@#_-'*65#6*65

	if len(char_freq)!=4:
		raise ValueError('char_freq must be 4 elements')
	if sum(char_freq)!=100:
		raise ValueError('char_freq sum must be 100')

	chars_list=list(al*char_freq[0]+au*char_freq[1]+n*char_freq[2]+s*char_freq[3])
	random.shuffle(chars_list)#打乱字符
	password=''
	for a in range(digit):
		password+=chars_list[random.randint(0,len(chars_list)-1)]
	return password
encrypt_pdfs(10,[30,30,30,10],
	r'D:\[CodePrograms]\Python_Primary_Programs\document_processing\pdf_processing\encrypt_pdfs\提问的智慧.pdf',
	r'D:\[CodePrograms]\Python_Primary_Programs\document_processing\pdf_processing\encrypt_pdfs\常用颜色色谱表.pdf',
	r'D:\[CodePrograms]\Python_Primary_Programs\document_processing\pdf_processing\encrypt_pdfs\导学.pdf')
